package com.rabbitmq.work.fair;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

//消费者
public class Producer {

    public static void main(String[] args) {

        //1. 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("47.122.113.100");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("123");
        factory.setVirtualHost("/");

        //2. 创建连接，通过连接获取通道
        Connection connection = null;
        Channel channel = null;
        try{
            connection = factory.newConnection();
            channel = connection.createChannel();


            //3. 声明交换机，队列，绑定队列到交换机
            String exchangeName = "Fair_test";
            channel.exchangeDeclare(exchangeName, "direct");
            channel.queueDeclare("queue7", false, false, false, null);
            channel.queueBind("queue7", exchangeName, "email");

            //4. 发送消息
            for (int i = 0; i < 20; i++) {
                String message = "Hello Work Mode Fair " + i;
                channel.basicPublish(exchangeName, "email",null, message.getBytes());
            }

            System.out.println("发送消息成功");

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            throw new RuntimeException(e);
        }finally {
            //5. 关闭资源
            if (channel != null && channel.isOpen()){
                try {
                    channel.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (TimeoutException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null && connection.isOpen()){
                try {
                    connection.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }

    }

}
